package com.tg.sieve_data.utils;

import org.apache.commons.lang3.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

public class HttpContextUtils {

	public static HttpServletRequest getHttpServletRequest() {
		return (HttpServletRequest) ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
	}

	public static String getDomain(){
		HttpServletRequest request = getHttpServletRequest();
		StringBuffer url = request.getRequestURL();
		return url.delete(url.length() - request.getRequestURI().length(), url.length()).toString();
	}

	public static String getOrigin(){
		HttpServletRequest request = getHttpServletRequest();
		return request.getHeader("Origin");
	}
	/**
	 * 获取客户端真实IP地址
	 * 考虑代理服务器的情况，优先从X-Forwarded-For和X-Real-IP头中获取
	 * @return 客户端真实IP地址
	 */
	public static String getIpAddress() {
		HttpServletRequest request = getHttpServletRequest();
		String ip = null;

		// 优先从X-Forwarded-For头获取IP地址
		ip = request.getHeader("X-Forwarded-For");
		if (StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
			// 从X-Real-IP头获取IP地址
			ip = request.getHeader("X-Real-IP");
		}

		// 如果还是没有获取到，再使用request.getRemoteAddr()
		if (StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getRemoteAddr();
		}

		// 对于通过多个代理的情况，X-Forwarded-For的值可能有多个IP，第一个IP为真实IP
		if (StringUtils.isNotEmpty(ip) && ip.contains(",")) {
			ip = ip.split(",")[0].trim();
		}

		return ip;
	}
}
